package com.osdp.auth.server.impl;

import com.osdp.auth.entity.User;
import com.osdp.auth.server.IUserService;
import com.osdp.common.exception.PlatformException;
import com.osdp.common.util.MessageUtil;
import com.osdp.sc.dto.TenantUserDTO;
import com.osdp.uc.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Value("${tenant.base.tenantId}")
    private String defaultTenantId;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        System.out.println("-----------account: "+ account);
        String userName = null;
        String tenantCode = null;
        if(account.contains("#")){
            String[] strs = account.split("#");
            if (strs.length < 2) {
                if(log.isErrorEnabled()){
                    log.error("用户信息未携带租户信息");
                }
                return null;
            }
            userName = strs[0];
            tenantCode = strs[1];
        }else{
            userName = account;
        }
        UserDTO userDTO = userService.queryUserByUserName(userName);
        if(userDTO == null){
            throw new PlatformException(MessageUtil.getMessage(10033));
        }
        List<TenantUserDTO> tenantUsers = userService.queryTenantByUserId(userDTO.getId());
        String currentTenantId = defaultTenantId;
        if (!StringUtils.isEmpty(tenantCode)) {
            currentTenantId = userService.getCurrentTenantId(tenantUsers, tenantCode);
        }
        List<String> tenantIds = userService.getTenantIds(tenantUsers);
        List<String> roleCodes = userService.getRoleCodeByUserId(userDTO.getId());
        User user = new User();
        user.setId(userDTO.getId());
        user.setUsername(userDTO.getUserName());
        user.setRealName(userDTO.getRealName());
        user.setPassword(userDTO.getPassWord());
        user.setSalt(userDTO.getSalt());
        user.setTenantId(currentTenantId);
        user.setTenantIds(tenantIds);
        user.setRoleCodes(roleCodes);
        if (userService.hasSuperAdmin(roleCodes)) {
            user.setSuperAdmin(true);
        }
        return user;
    }
}
